package com.blog.blogservice.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.blogservice.app.service.LabelService;
import com.blog.blogservice.domain.entity.Label;
import com.blog.blogservice.infra.mapper.LabelMapper;
import com.blog.blogservice.util.constant.BlogConstant;
import org.apache.ibatis.executor.BatchResult;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签表(Label)应用服务
 *
 * @author guanglin.ma
 * @since 2024-03-02 23:25:50
 */
@Service
public class LabelServiceImpl extends ServiceImpl<LabelMapper, Label> implements LabelService {

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询数据
     *
     * @param labels 查询条件
     * @return 返回值
     */
    @Override
    public List<Label> selectList(Label labels) {
        QueryWrapper queryWrapper = new QueryWrapper<Label>();
        return labelMapper.selectList(queryWrapper);
    }

    /**
     * 保存数据
     *
     * @param labels 数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Label> saveData(List<Label> labels) {
        labels.forEach(label -> label.setLabelCode(BlogConstant.LABEL_CODE_PREFIX + System.currentTimeMillis()));
        List<BatchResult> batchResultList = labelMapper.insertBathch(getSqlSessionFactory(), labels, LabelMapper.class);
        List<Label> labelList = batchResultList.get(0).getParameterObjects().stream().map(o -> (Label) o).collect(Collectors.toList());
        //此处虽然是有循环，但是实际数据只有一个，所以不考虑redis网络延迟
        HashMap hashMap = new HashMap<>();
        labelList.forEach(label -> {
            hashMap.put(label.getLabelCode(), label.getLabelName());
        });
        redisTemplate.opsForHash().putAll(BlogConstant.LABEL_LIST, hashMap);
        return labelList;
    }

    @Override
    public void deleteData(List<Label> labels) {
        if (!CollectionUtils.isEmpty(labels)) {
            labels.forEach(label -> this.removeById(label.getLabelId()));
        }
    }

    /**
     * 查询列表
     *
     * @param queryWrapper 实体对象封装操作类 {@link QueryWrapper}
     */
    @Override
    public List<Label> listQueryWrapper(Wrapper<Label> queryWrapper) {
        return super.list(queryWrapper);
    }
}

